package com.dufang.thread01Create;

/*
   volatile的可见性探索
 */
public class VolatileTest {
    public static void main(String[] args) {
        Task task = new Task();

        Thread t1=new Thread(task,"线程t1");
        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(1000L);
                    System.out.println("开始通知线程停止");
                    task.stop=true;//修改stop变量
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });

    }
}

/**
 * votalite保证了变量对所有线程的可见性;另一个作用：禁止指令重排，不保证原子性
 */
class Task implements Runnable{
       volatile boolean stop=false;
        int i=0;

        @Override
        public void run(){
            long s=System.currentTimeMillis();
            while(!stop){
                i++;
            }
            System.out.println("线程退出"+(System.currentTimeMillis()-s));
        }
    }
